import { defineStore } from "pinia"; // 定义容器
import { ref, computed, reactive } from 'vue';
import { getDictSelect } from '@/api/index.js';

//  标题名称
export const usePageTitle = defineStore('pageTitle', () => {
  //  data
  const pageTitle = ref('');

  //  methods
  function setPageTitle(val) {
    pageTitle.value = val;
  }

  return { pageTitle, setPageTitle }
})

//  字典项集合
export const useDictSelect = defineStore('dictSelectArray', () => {
  //  data
  const dictSelectArray = reactive({});

  //  methods
  async function setDictSelect(type) {
    return new Promise(async (resolve, reject) => {
      //  判断之前是否存在，存在则不需要重新加载
      if (dictSelectArray[type]) {
        resolve(dictSelectArray[type]);
        return;
      } 

      dictSelectArray[type] = await getDictFn(type);
      resolve(dictSelectArray[type]);
    })
  }

  //  更新 dict
  async function refreshDictSelect(type) {
    dictSelectArray[type] = await getDictFn(type);
  }

  //  获取数据
  async function getDictFn(type) {
    const { code, data } = await getDictSelect(type);
    if (code === 200) {
      return data;
    }
  }

  return { dictSelectArray, setDictSelect }
})